package com.xhl.shiro.datasource.aspect;

import com.xhl.shiro.datasource.annotation.DataSource;
import com.xhl.shiro.datasource.utils.DynamicContextUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Objects;

/**
 * 多数据源，切面处理类
 *
 * @author lisk wlsk131420@gmail.com
 */
@Aspect
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class DataSourceAspect {
    protected Logger logger = LoggerFactory.getLogger(DataSourceAspect.class);

    @Pointcut("@annotation(com.xhl.shiro.datasource.annotation.DataSource)" +
            "|| @within(com.xhl.shiro.datasource.annotation.DataSource)")
    public  void dataSourcePointCut(){

    }

    @Around("dataSourcePointCut()")
    public  Object around(@NotNull ProceedingJoinPoint point) throws Throwable{
        MethodSignature signature = (MethodSignature) point.getSignature();
        Class targetClass = point.getTarget().getClass();
        Method method = signature.getMethod();

        DataSource targetDataSource = (DataSource) targetClass.getAnnotation(DataSource.class);
        DataSource methodDataSource = method.getAnnotation(DataSource.class);
        if(Objects.nonNull(targetDataSource) || Objects.nonNull(methodDataSource)){

            String value = Objects.nonNull(methodDataSource) ? methodDataSource.value() : targetDataSource.value();
            DynamicContextUtils.push(value);
            logger.debug("set datasource is {}", value);
        }

        try{
            return point.proceed();
        }finally {
            DynamicContextUtils.poll();
            logger.info("clean datasource");
        }
    }
}
